'use strict';
const constant = require('./const');
const semver = require('semver');
const colors = require('colors');
const log = require('@dou-gong-cli/log');

class command {
  constructor(argv) {
    /** 参数类型检查
    -------------------------------------- */
    if (!argv) {
      throw new Error('参数不能为空');
    }
    if (!Array.isArray(argv)) {
      throw new Error('参数必须是数组');
    }
    if (argv.length < 1) {
      throw new Error('参数列表为空');
    }

    this._argv = argv;
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      chain = chain.then(() => this.checkNodeVersion());
      chain = chain.then(() => this.initArgv());
      chain = chain.then(() => this.init());
      chain = chain.then(() => this.exec());
      chain.catch((e) => log.error('command', e.message));
    });
  }

  init() {
    throw new Error('继承的command类必须重新init方法');
  }

  exec() {
    throw new Error('继承的command类必须重新exec方法');
  }

  /** 检查Node版本 */
  checkNodeVersion() {
    // 1.获取当前Node版本号
    // 2.比对当前版本号和最低要求Node版本号
    const currentVersion = process.version;
    const lowestVersion = constant.LOWEST_NODE_VERSION;

    if (semver.lt(currentVersion, lowestVersion)) {
      throw new Error(colors.red(`最低支持的Node版本号：${lowestVersion}`));
    }
  }

  /** 初始化参数列表 */
  initArgv() {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
  }
}

module.exports = command;
